package com.yocard.yxyd.ui.activity;

import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.umeng.analytics.MobclickAgent;
import com.yocard.yxyd.R;
import com.yocard.yxyd.base.AppContext;
import com.yocard.yxyd.base.Constants;
import com.yocard.yxyd.http.Api;
import com.yocard.yxyd.http.model.base.Response;
import com.yocard.yxyd.http.model.response.CommonBean;
import com.yocard.yxyd.http.model.response.CsmPayInfo;
import com.yocard.yxyd.http.model.response.OrderListBean;
import com.yocard.yxyd.http.model.response.OrderPayResponseBean;
import com.yocard.yxyd.http.model.response.UserInfoBean;
import com.yocard.yxyd.ui.activity.base.BaseActivity;
import com.yocard.yxyd.ui.contract.OrderDetailContact;
import com.yocard.yxyd.ui.dialog.CommonDialog;
import com.yocard.yxyd.ui.dialog.PayDialog;
import com.yocard.yxyd.ui.dialog.ShareDialog;
import com.yocard.yxyd.ui.presenter.OrderDetailPresenter;
import com.yocard.yxyd.ui.view.ObservableScrollView;
import com.yocard.yxyd.utils.BigDecimalUtil;
import com.yocard.yxyd.utils.CommonUtils;
import com.yocard.yxyd.utils.constant.CacheConstants;
import com.yocard.yxyd.utils.util.ActivityUtils;
import com.yocard.yxyd.utils.util.ConvertUtils;
import com.yocard.yxyd.utils.util.SPUtils;
import com.yocard.yxyd.utils.util.TimeUtils;
import com.yocard.yxyd.utils.util.ToastUtils;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import static com.yocard.yxyd.event.EventCode.REFRESH_ORDER_LIST;

/**
 * Created on 2019/4/8.
 */
public class OrderDetailActivity extends BaseActivity<OrderDetailPresenter> implements OrderDetailContact.View {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.tv_periord)
    TextView tvPeriord;
    @BindView(R.id.tv_loan_type)
    TextView tvLoanType;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.tv_zhiye)
    TextView tvZhiye;
    @BindView(R.id.ll_container)
    LinearLayout llContainer;
    @BindView(R.id.flow_ziliao)
    TagFlowLayout flowLayout;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.iv_call)
    ImageView ivCall;
    @BindView(R.id.rl_head_layout)
    RelativeLayout rlHeadLayout;
    @BindView(R.id.scroll_view)
    ObservableScrollView scrollView;

    protected String orderId;
    private OrderListBean.OrderList orderListBean;
    protected String mobile;
    private PayDialog payDialog;

    private ShareDialog shareDialog;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.act_order_detail;
    }

    @Override
    protected void initEventAndData() {
        ImmersionBar.with(this).statusBarColor(R.color.white)
                .statusBarDarkFont(true).navigationBarColor(R.color.white).init();
        Bundle data = getIntent().getExtras();
        if (data != null) {
            orderId = (String) data.getSerializable("data");
        }
        Uri uri = getIntent().getData();
        if(uri != null) {
            orderId = uri.getQueryParameter("orderId");
        }
        showLoadingDialog();
        mPresenter.fetchData(orderId);
        initHead();
    }

    private void initHead() {
        float yOffset = ConvertUtils.dp2px(74);
        scrollView.setOnScollChangedListener(new ObservableScrollView.OnScollChangedListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                float v = y / yOffset;
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_commit, R.id.iv_call, R.id.tv_share_order})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ActivityUtils.finishActivity(this);
                break;
            case R.id.tv_commit:
                //防止短时间重复点击
                if (isFastDoubleClick()) return;

                MobclickAgent.onEvent(mContext, "1", "click_qiangdan");
                showLoadingDialog();
                tvCommit.setEnabled(false);
                mPresenter.fetchUserData();
                break;
            case R.id.tv_share_order:
                if (shareDialog == null) {
                    shareDialog = new ShareDialog(this, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {
                            if (ShareDialog.MOMENTS.equals(value)) {
                                showShare(WechatMoments.NAME);
                                return;
                            }
                            if (shareDialog.WE_CHAT.equals(value)) {
                                showShare(Wechat.NAME);
                            }
                        }
                    });
                }
                shareDialog.show();
                break;
            case R.id.iv_call:
                CommonDialog.Builder builder = new CommonDialog.Builder(mContext).setTitle(mobile)
                        .setLeftText("取消")
                        .setRightText("拨打")
                        .setListener(pos -> {
                            if (pos == CommonDialog.CLICK_POS_RIGHT) {
                                CommonUtils.callPhone(mContext, mobile);
                            }
                        });
                builder.show();
                break;
        }
    }

    public void showShare(String platform) {
        String url = orderListBean.getShare_url();
        final OnekeyShare oks = new OnekeyShare();
        //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
        if (platform != null) {
            oks.setPlatform(platform);
        }
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle(orderListBean.getCity().getName() + "的" + orderListBean.getName() + "刚发布了条" + orderListBean.getLoan_amount() + "万的" + CommonUtils.getLoanTypeStr(orderListBean.getLoan_type()) +"需求，正在寻找贷款渠道～");
        // text是分享文本，所有平台都需要这个字段
//        oks.setText("免费抢单啦！我刚在优单上获得免单，邀请您一起获取优质贷款客户");
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams shareParams) {
//                shareParams.setText("免费抢单啦！我刚在优单上获得免单，邀请您一起获取优质贷款客户");
//                shareParams.setTitle("优单-信贷经理的展业利器，注册认证即送礼");
                shareParams.setTitleUrl(url);
                shareParams.setUrl(url);
                shareParams.setImageData(BitmapFactory.decodeResource(AppContext.getContext().getResources(), R.mipmap.ico_share));
                shareParams.setShareType(Platform.SHARE_WEBPAGE);
            }
        });
        oks.show(this);
    }

    @Override
    public void onFetchData(OrderListBean.OrderList orderListBean) {
        this.orderListBean = orderListBean;
        dismisDialog();
        mobile = orderListBean.getMobile();
        tvName.setText(orderListBean.getName());
        tvTime.setText("申请时间：" + TimeUtils.millis2String(orderListBean.getCheck_at() * 1000, TimeUtils.DATE_TIME_STYLE1));
        tvAmount.setText(orderListBean.getAmount());
        tvPeriord.setText(CommonUtils.getMonth(orderListBean.getLoan_period()));
        tvLoanType.setText(CommonUtils.getLoanTypeStr(orderListBean.getLoan_type()));
        tvMobile.setText(mobile);
        if(orderListBean.getCity() != null){
            tvCity.setText(orderListBean.getCity().getName());
        }
        tvAge.setText(orderListBean.getAge() + "岁");
        tvZhiye.setText(CommonUtils.getCareerStr(orderListBean.getCareer()));
        mPresenter.fillView(llContainer, orderListBean);

        List<String> ziliao = CommonUtils.getZiliao(orderListBean);
        mPresenter.fillZiliao(flowLayout, ziliao);
//        tvPrice.setText(BigDecimalUtil.getFormatCoin(orderListBean.getPrice()) + "金币");
        tvPrice.setText(String.format(getString(R.string.price_pay_prefix), BigDecimalUtil.getFormatCoin(orderListBean.getPrice())));

        int status = orderListBean.getStatus();
        if (status == 1) {
            tvCommit.setText("已被抢");
            tvCommit.setEnabled(false);
        }

        if (mobile.contains("*")) {
            ivCall.setEnabled(false);
        } else {
            ivCall.setEnabled(true);
        }
    }

    @Override
    public void onFetchUser(UserInfoBean data) {
        if (data != null)
            SPUtils.getInstance().put(Constants.USER_PHONE, data.getId());
        tvCommit.setEnabled(true);
        if (Constants.AUTH_APPROVED.equals(data.getApproval_status())) {
            if (BigDecimalUtil.compareTo(data.getCoin_balance(), orderListBean.getPrice()) != -1) {
                //下一步
                mPresenter.commit(orderId);
            } else {
                dismisDialog();
                CommonDialog.Builder builder = new CommonDialog.Builder(mContext)
                        .setTitle("当前账户余额不足")
                        .setLeftText("取消")
                        .setRightText("充值")
                        .setLogo(R.mipmap.ic_kedan_recharge)
                        .setListener(buttonPos -> {
                            if (CommonDialog.CLICK_POS_RIGHT == buttonPos) {
                                ActivityUtils.startActivity(TopupCenterActivity.class);
                            }
                        });
                builder.show();
            }
        } else {
            dismisDialog();
            if (Constants.AUTH_APPROVING.equals(data.getApproval_status())) {
                ToastUtils.showLong(R.string.certifying_tips);
            } else {
                CommonDialog.Builder builder = new CommonDialog.Builder(mContext)
                        .setTitle("您尚未完成认证！ \n认证成功才能抢单噢～")
                        .setLeftText("暂不认证")
                        .setRightText("立即认证")
                        .setLogo(R.mipmap.ic_kedan_unverified)
                        .setListener(buttonPos -> {
                            if (CommonDialog.CLICK_POS_RIGHT == buttonPos) {
                                ActivityUtils.startActivity(CertificationActivity.class);
                            }
                        });
                builder.show();
            }
        }
    }

    @Override
    public void onCreatedOrder(String id) {
        EventBus.getDefault().post(new CommonBean(Constants.CODE_REFRESH));

        tvCommit.setEnabled(true);
        dismisDialog();
//        Bundle bundle = new Bundle();
//        bundle.putString("id", id);
//        ActivityUtils.startActivity(bundle, SettlementActivity.class);
        //修改为弹窗支付
        showPayDialog(id);
    }

    private void showPayDialog(String id) {
        if(payDialog == null) {
            payDialog = new PayDialog(this, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    MobclickAgent.onEvent(mContext,"3","click_coin_pay");
                    if(TextUtils.isEmpty(value)) {
                        ToastUtils.showShort(R.string.cancel_pay);
                        return;
                    }
                    showLoadingDialog();
                    int delay = orderListBean.getIs_virtual() == 1 ? 2 : 0;
                    mPresenter.doPay(id, delay);
                }
            }, BigDecimalUtil.getFormatCoin(orderListBean.getPrice()));
        }
        payDialog.show();
    }

    @Override
    public void onFetchOrderData(CsmPayInfo csmOrderBean) {
        dismisDialog();
//        try {
//            tvName.setText(csmOrderBean.getSheets().getName());
//            tvBigPrice.setText(BigDecimalUtil.getFormatCoin(csmOrderBean.getReal_coin_price()));
//            tvPrice.setText(BigDecimalUtil.getFormatCoin(csmOrderBean.getReal_coin_price()) + "金币");
//            tvTime.setText("申请时间：" + TimeUtils.millis2String(csmOrderBean.getSheets().getApplied_at() * 1000));
//            tvAmount.setText(csmOrderBean.getSheets().getAmount());
//            tvPeriord.setText(csmOrderBean.getSheets().getLoan_period());
//            tvLoanType.setText(CommonUtils.getLoanTypeStr(csmOrderBean.getSheets().getLoan_type()));
//            tvBalance.setText("(" + BigDecimalUtil.getFormatCoin(csmOrderBean.getCoin_balance()) + "金币)");
//        }catch (Exception e){
//
//        }
    }

    @Override
    public void onPaySuccess(OrderPayResponseBean data) {
        EventBus.getDefault().post(new CommonBean(Constants.CODE_REFRESH));
        EventBus.getDefault().post(new CommonBean(3));
        EventBus.getDefault().post(new CommonBean(REFRESH_ORDER_LIST));
        dismisDialog();
        Bundle bundle = new Bundle();
        bundle.putBoolean("isSuccess", true);
        bundle.putString("id",data.getId() + "");
        ActivityUtils.startActivity(bundle, SettleResultActivity.class);
        ActivityUtils.finishActivity(this);
    }

    @Override
    public void onPayFailed(String msg) {
        dismisDialog();
        ToastUtils.showLong(msg);
        EventBus.getDefault().post(new CommonBean(Constants.CODE_REFRESH));
        Bundle bundle = new Bundle();
        bundle.putBoolean("isSuccess", false);
        bundle.putString("id",orderId);
        ActivityUtils.startActivity(bundle, SettleResultActivity.class);
        ActivityUtils.finishActivity(this);
    }

    @Override
    public void onOrderReceived(Response response) {
        EventBus.getDefault().post(new CommonBean(Constants.CODE_REFRESH));
        EventBus.getDefault().post(new CommonBean(3));
        EventBus.getDefault().post(new CommonBean(REFRESH_ORDER_LIST));
        dismisDialog();
        ToastUtils.showShort(response.getMessage());
//        if(orderListBean.getIs_virtual() == 1) {
//            tvCommit.setText("已被抢");
//            tvCommit.setEnabled(false);
//        }
    }

    @Override
    public void showErrorMsg(String msg) {
        super.showErrorMsg(msg);
        tvCommit.setEnabled(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStatus(CommonBean bean) {
        if (bean.getCode() == 3) {
            tvCommit.setText("已被抢");
            tvCommit.setEnabled(false);
        } else if (bean.getCode() == 4) {
            ActivityUtils.finishActivity(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
